
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>SlideShow</title>
    </head>
    <body>
        <h1>Upload de PPT</h1>
        <%@ page import="java.io.*" %>
        <%@ page import="java.awt.Color" %>
        <%@ page import="java.awt.Dimension" %>
        <%@ page import="java.awt.Graphics2D" %>
        <%@ page import="java.awt.geom.Rectangle2D" %>
        <%@ page import="java.awt.image.BufferedImage" %>
        <%@ page import="java.io.FileInputStream" %>
        <%@ page import="java.io.FileOutputStream" %>
        <%@ page import="org.apache.poi.hslf.model.Slide" %>
        <%@ page import="org.apache.poi.hslf.usermodel.SlideShow" %>
        <%@ page import="java.sql.*" %>
        <%@ page import="com.eaio.uuid.*" %>

        <%

        ///CONFIGS
        String ip_server = "localhost";                           //ip do apache q vai armazenar os jpg
        String bd_url = "jdbc:mysql://localhost:3306/opensim"; //url do mysql
        String bd_user = "root";                                //user do mysql
        String bd_senha = "senha";                               //senha do mysql
        String UserName = "Test";                                //usuario q esta mandando o ppt
        String LastName = "User";                                //usuario q esta mandando o ppt
        String path_upload = "C:\\inetpub\\wwwroot\\";              //caminho real de onde vai salvar os .jpg e o ppt q foi enviado

        try {

            String contentType = request.getContentType();
            System.out.println("Content type is :: " + contentType);

            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                DataInputStream in = new DataInputStream(request.getInputStream());
                int formDataLength = request.getContentLength();

                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                while (totalBytesRead < formDataLength) {
                    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += byteRead;
                }

                String file = new String(dataBytes);
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

                if (!saveFile.endsWith(".ppt")) {
                    out.println("Erro: Somente arquivos ppt");
                } else {
                    int lastIndex = contentType.lastIndexOf("=");
                    String boundary = contentType.substring(lastIndex + 1, contentType.length());
                    //out.println(boundary);
                    int pos;
                    pos = file.indexOf("filename=\"");

                    pos = file.indexOf("\n", pos) + 1;

                    pos = file.indexOf("\n", pos) + 1;

                    pos = file.indexOf("\n", pos) + 1;


                    int boundaryLocation = file.indexOf(boundary, pos) - 4;
                    int startPos = ((file.substring(0, pos)).getBytes()).length;
                    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                    String saveFileCompleto = path_upload + saveFile;
                    FileOutputStream fileOut = new FileOutputStream(saveFileCompleto);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();

                    out.println("<h2>Salvando arquivo</h2>");
                    out.println("Arquivo salvo: " + saveFile);


                    //abre ppt
                    FileInputStream is = new FileInputStream(saveFileCompleto);
                    SlideShow ppt = new SlideShow(is);
                    is.close();

                    Dimension pgsize = ppt.getPageSize();

                    Slide[] slide = ppt.getSlides();


                    //FAZ JPG PARA CADA SLIDE
                    for (int i = 0;
                            i < slide.length;
                            i++) {
                        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                        Graphics2D graphics = img.createGraphics();
                        //clear the drawing area
                        graphics.setPaint(Color.white);
                        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

                        //render
                        slide[i].draw(graphics);

                        //save the output
                        FileOutputStream outS = new FileOutputStream(path_upload + saveFile + "slide-" + (i + 1) + ".jpg");
                        javax.imageio.ImageIO.write(img, "jpg", outS);
                        outS.close();
                    }
                    //FAZ JPG PARA CADA SLIDE

                    //CRIA LSL

                    String scriptLSL = "integer count = 0;\n";

                    for (int i = 1; i < slide.length + 1; i++) {
                        scriptLSL += "string URL" + i + " = \"http://" + ip_server + "/" + saveFile + "slide-" + i + ".jpg\";\n";
                    }
                    scriptLSL += "\nstring dynamicID=\"\";\n" +
                            "string contentType=\"image\";\n" +
                            "\nrefresh_texture(integer cima){\n" +
                            "\tif(cima == 1) {\n" +
                            "\t\tcount++;\n" +
                            "\t} else {\n" +
                            "\t\tcount--;\n\t}\n" +
                            "\n\tstring url = \"\";\n" +
                            "\n\tinteger c = count % " + (slide.length) + ";\n";
                    for (int i = 1; i < slide.length + 1; i++) {
                        scriptLSL += "\tif(c == " + i + ") {" +
                                "\n\t\turl = URL" + i +
                                ";\n\t}\n";
                    }

                    scriptLSL += "\tosSetDynamicTextureURL(dynamicID, contentType, url, \"\", 0);\n" +
                            "}\n\n" +
                            "default{\n" +
                            "\tstate_entry(){\n" +
                            "\t\tllListen(30, \"\", NULL_KEY, \"\");\n" +
                            "\t\tllListen(20, \"\", NULL_KEY, \"\");\n" +
                            "\t\trefresh_texture(1);\n\t}\n" +
                            "\t\tlisten(integer channel, string name, key id, string message){\n" +
                            "\t\tif(id == llGetOwner()) {\n" +
                            "\t\t\tif(channel == 30) {\n" +
                            "\t\t\t\trefresh_texture(1);\n" +
                            "\t\t\t} else if (channel == 20) {\n" +
                            "\t\t\t\trefresh_texture(0);\n" +
                            "\t\t\t}\n\t\t}\n\t}\n}";

                    out.println("<h2>ScriptLSL</h2><br><pre>" + scriptLSL + "</pre>");
                    //CRIA LSL

                    //POE NO OPENSIM
                    out.println("<h2>Linkando com usuario</h2>");

                    Statement stmt;
                    ResultSet rs;

                    Class.forName("com.mysql.jdbc.Driver");

                    String url = bd_url;

                    Connection con = DriverManager.getConnection(url, bd_user, bd_senha);

                    //Display URL and connection information
                    //System.out.println("URL: " + url);
                    //System.out.println("Connection: " + con);

                    //Get a Statement object
                    stmt = con.createStatement();

                    //1-) Pego qual o UUID do usuario
                    rs = stmt.executeQuery("SELECT UUID FROM users WHERE username='" + UserName + "' AND lastname='" + LastName + "';");
                    rs.next();
                    String uuid_user = rs.getString("UUID");
                    //System.out.println("UUID do Usuario: " + uuid_user);


                    //2-)Pega qual o UUID do registro Folders "Scripts" do usuario em inventoryfoldes
                    rs = stmt.executeQuery("SELECT folderID FROM inventoryfolders WHERE agentID='" + uuid_user + "' AND folderName='Scripts';");
                    rs.next();
                    String uuid_folder = rs.getString("folderID");
                    //System.out.println("UUID do Inventario: " + uuid_folder);


                    //3-) Crio um script com UUID novo, e nome do Script (aka SlideShow-nomedoPPT), descricao, datastamp pra create_time e access_time, e a data
                    UUID uuid_asset = new UUID();
                    String nome_script = "SlideShow - " + saveFile;
                    String descricao_script = "SlideShow - " + saveFile;
                    String data = scriptLSL;
                    stmt.executeUpdate("insert INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, data) VALUES " +
                            "('" + uuid_asset + "', '" + nome_script + "', '" + descricao_script + "', 10, 0, 0, 1241082211, 1241082211, _binary '" + data + "')");
                    //System.out.println("Criado asset: " + uuid_asset);


                    //4-) Ligo o script criado com o invertario do usuario
                    UUID uuid_inventory = new UUID();
                    stmt.executeUpdate("REPLACE INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID," +
                            " inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType," +
                            " creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions," +
                            " salePrice, saleType, creationDate, groupID, groupOwned, flags) VALUES " +
                            "('" + uuid_inventory + "', '" + uuid_asset + "', '10', '" + uuid_folder + "'," +
                            " '" + uuid_user + "', '" + nome_script + "', '" + descricao_script + "', '532480'," +
                            " '2147483647', 10, '" + uuid_user + "', 2147483647, 0, 0, 0, 0, 1241093011," +
                            " _binary '00000000-0000-0000-0000-000000000000', 0, 0)");
                    //System.out.println("UUID do inventario:" + uuid_inventory);
                    //System.out.println("Ligado script com inventario");


                    //5-) Atualizo a versão do inventario
                    stmt.executeUpdate("update inventoryfolders set version=version+1 where folderID = '" + uuid_folder + "'");
                    //System.out.println("Atualizada versão do folder");

                    //System.out.println("reinicie o cliente");

                    con.close();
                    out.println("Linkado com user");
                //POE NO OPENSIM



                }
            }

        } catch (IOException e) {
            out.println("Erro ao salvar arquivo no servidor");
            out.println(e.getMessage());
        } catch (SQLException e) {
            out.println("Erro com o banco de dados");
            out.println(e.getMessage());
        } catch (Exception e) {
            out.println("Erro");
            out.println(e.getMessage());
        }
        %>

    </body>
</html>
